/**
 * list -> tree
 * @param array{}
 * @param prop
 * @returns
 */
export const toTree = (array: any[], prop = {id: 'id', pid: 'pid', children: 'children'}) => {
  const result : any[] = []
  if (!Array.isArray(array)) {
    return result
  }
  array.forEach(item => {
    delete item[prop.children]
  })
  const map: any = {}
  array.forEach(item => {
    map[item[prop.id]] = item
  })
  array.forEach(item => {
    const parent = map[item[prop.pid]]
    if (parent) {
      (parent[prop.children] || (parent[prop.children] = [])).push(item)
    } else {
      result.push(item)
    }
  })
  return result
}

/**
 * 获取含children的数据类型的id的item
 * @param treeData
 * @param id
 * @param prop
 * @returns {null}
 */
export const getTreeItem = (treeData: any, id: any, prop = {id: 'id', pid: 'pid', children: 'children'}) :any => {
  let result = null
  if (!treeData) {
    return {}
  }
  for (let i = 0; i < treeData.length; i++) {
    if (result !== null) {
      break
    }
    const item = treeData[i]
    if (item[prop.id] === id) {
      result = item
      break
    } else if (item[prop.children]) {
      result = getTreeItem(item[prop.children], id, prop)
    }
  }
  return result
}
